/**
 * Created by Ysssssss on 2021/5/4.
 */

import React, { useEffect, useRef } from 'react';
import { useDrag, useDrop } from 'react-dnd';

export const CustomizeDragTarget = (props) => {
    const { id, type, className, children, onDrop } = props
    const [{ opacity }, drag] = useDrag(() => ({
        type,
        item: { id },
        end(item, monitor) {
            const dropResult = monitor.getDropResult();
            if (item && dropResult) {
                onDrop(dropResult.index)
            }
        },
        collect: (monitor) => ({
            opacity: monitor.isDragging() ? 0.4 : 1,
        }),
    }), [id]);
    return (
        <div className={className} ref={drag} style={{ opacity }}>
            { children }
        </div>
    );
};

export const CustomizeDropTarget = (props) => {
    const { className, type, index, children } = props

    const [{ canDrop, isOver }, drop] = useDrop(() => ({
        accept: type,
        drop: () => ({
            index
        }),
        collect: (monitor) => ({
            isOver: monitor.isOver(),
            canDrop: monitor.canDrop(),
        }),
    }), [index]);
    const isActive = canDrop && isOver;

    return (
        <div ref={drop} className={`${className}${canDrop ? '' : ' hidden'}${isActive ? ' bd-green' : ''}`}>
            { children }
        </div>
    )
}